package org.csu.onlineedubackend.controller;

import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.entity.Lesson;
import org.csu.onlineedubackend.entity.StudentCourseDanmaku;
import org.csu.onlineedubackend.entity.VideoStudentCourseProgress;
import org.csu.onlineedubackend.mapper.LessonMapper;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.LessonService;
import org.csu.onlineedubackend.service.StudentCourseVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/student/video")
@Slf4j
public class StudentCourseVideoController {

    @Autowired
    private StudentCourseVideoService videoService;
    
    @Autowired
    private LessonService lessonService;
    
    @Autowired
    private LessonMapper lessonMapper;

    /**
     * 获取视频播放进度
     */
    @GetMapping("/progress")
    public CommonResponse<?> getVideoProgress(
            @RequestParam Integer studentId,
            @RequestParam Integer lessonId) {
        log.info("获取视频播放进度 - 学生ID: {}, 课时ID: {}", studentId, lessonId);
        
        try {
            // 检查课时是否存在
            Lesson lesson = lessonService.getById(lessonId);
            if (lesson == null) {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课时不存在");
            }
            
            // 获取视频播放进度
            VideoStudentCourseProgress progress = videoService.getVideoProgress(studentId, lessonId);
            
            if (progress == null) {
                // 如果没有进度记录，返回默认值
                Map<String, Object> defaultProgress = new HashMap<>();
                defaultProgress.put("currentTime", 0);
                defaultProgress.put("isCompleted", false);
                defaultProgress.put("playbackRate", 1.0f);
                defaultProgress.put("qualitySetting", "auto");
                defaultProgress.put("subtitleEnabled", false);
                defaultProgress.put("volume", 1.0f);
                defaultProgress.put("danmakuEnabled", true);
                defaultProgress.put("pipEnabled", false);
                
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取成功", defaultProgress);
            }
            
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取成功", progress);
        } catch (Exception e) {
            log.error("获取视频播放进度失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "获取视频播放进度失败");
        }
    }

    /**
     * 更新视频播放进度
     */
    @PostMapping("/progress")
    public CommonResponse<?> updateVideoProgress(
            @RequestBody VideoStudentCourseProgress progress) {
        log.info("更新视频播放进度 - 学生ID: {}, 课时ID: {}, 当前时间: {}", 
                progress.getStudentId(), progress.getLessonId(), progress.getCurrentTime());
        
        try {
            boolean result = videoService.updateVideoProgress(progress);
            if (result) {
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "更新成功", null);
            } else {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "更新失败");
            }
        } catch (Exception e) {
            log.error("更新视频播放进度失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "更新视频播放进度失败");
        }
    }

    /**
     * 标记视频为已完成
     */
    @PostMapping("/complete")
    public CommonResponse<?> markVideoCompleted(
            @RequestParam Integer studentId,
            @RequestParam Integer lessonId) {
        log.info("标记视频为已完成 - 学生ID: {}, 课时ID: {}", studentId, lessonId);
        
        try {
            boolean result = videoService.markVideoCompleted(studentId, lessonId);
            if (result) {
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "标记成功", null);
            } else {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "标记失败");
            }
        } catch (Exception e) {
            log.error("标记视频为已完成失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "标记视频为已完成失败");
        }
    }

    /**
     * 更新视频播放设置
     */
    @PostMapping("/settings")
    public CommonResponse<?> updateVideoSettings(
            @RequestParam Integer studentId,
            @RequestParam Integer lessonId,
            @RequestParam(required = false) Float playbackRate,
            @RequestParam(required = false) String qualitySetting,
            @RequestParam(required = false) Boolean subtitleEnabled) {
        log.info("更新视频播放设置 - 学生ID: {}, 课时ID: {}, 播放速度: {}, 清晰度: {}, 字幕: {}", 
                studentId, lessonId, playbackRate, qualitySetting, subtitleEnabled);
        
        try {
            boolean result = videoService.updateVideoSettings(studentId, lessonId, playbackRate, qualitySetting, subtitleEnabled);
            if (result) {
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "更新成功", null);
            } else {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "更新失败");
            }
        } catch (Exception e) {
            log.error("更新视频播放设置失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "更新视频播放设置失败");
        }
    }
    
    /**
     * 更新视频高级设置
     */
    @PostMapping("/advanced-settings")
    public CommonResponse<?> updateAdvancedSettings(
            @RequestParam Integer studentId,
            @RequestParam Integer lessonId,
            @RequestParam(required = false) Float volume,
            @RequestParam(required = false) Boolean danmakuEnabled,
            @RequestParam(required = false) Boolean pipEnabled) {
        log.info("更新视频高级设置 - 学生ID: {}, 课时ID: {}, 音量: {}, 弹幕: {}, 画中画: {}", 
                studentId, lessonId, volume, danmakuEnabled, pipEnabled);
        
        try {
            boolean result = videoService.updateAdvancedSettings(studentId, lessonId, volume, danmakuEnabled, pipEnabled);
            if (result) {
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "更新成功", null);
            } else {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "更新失败");
            }
        } catch (Exception e) {
            log.error("更新视频高级设置失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "更新视频高级设置失败");
        }
    }
    
    /**
     * 获取视频详情
     */
    @GetMapping("/detail")
    public CommonResponse<?> getVideoDetail(
            @RequestParam Integer lessonId,
            @RequestParam Integer studentId) {
        log.info("获取视频详情 - 课时ID: {}, 学生ID: {}", lessonId, studentId);
        
        try {
            // 获取课时信息
            Lesson lesson = lessonService.getById(lessonId);
            if (lesson == null) {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课时不存在");
            }
            
            // 获取视频播放进度
            VideoStudentCourseProgress progress = videoService.getVideoProgress(studentId, lessonId);
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("lesson", lesson);
            result.put("progress", progress);
            
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取成功", result);
        } catch (Exception e) {
            log.error("获取视频详情失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "获取视频详情失败");
        }
    }
    
    /**
     * 获取课时弹幕列表
     */
    @GetMapping("/danmaku")
    public CommonResponse<?> getDanmakusByLessonId(
            @RequestParam Integer lessonId) {
        log.info("获取课时弹幕列表 - 课时ID: {}", lessonId);
        
        try {
            // 检查课时是否存在
            Lesson lesson = lessonService.getById(lessonId);
            if (lesson == null) {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课时不存在");
            }
            
            // 获取弹幕列表
            List<StudentCourseDanmaku> danmakuList = videoService.getDanmakusByLessonId(lessonId);
            
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取成功", danmakuList);
        } catch (Exception e) {
            log.error("获取课时弹幕列表失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "获取课时弹幕列表失败");
        }
    }
    
    /**
     * 获取指定时间范围内的弹幕列表
     */
    @GetMapping("/danmaku/range")
    public CommonResponse<?> getDanmakusByTimeRange(
            @RequestParam Integer lessonId,
            @RequestParam Integer startTime,
            @RequestParam Integer endTime) {
        log.info("获取指定时间范围内的弹幕列表 - 课时ID: {}, 开始时间: {}, 结束时间: {}", 
                lessonId, startTime, endTime);
        
        try {
            // 检查课时是否存在
            Lesson lesson = lessonService.getById(lessonId);
            if (lesson == null) {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课时不存在");
            }
            
            // 获取弹幕列表
            List<StudentCourseDanmaku> danmakuList = 
                    videoService.getDanmakusByTimeRange(lessonId, startTime, endTime);
            
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取成功", danmakuList);
        } catch (Exception e) {
            log.error("获取指定时间范围内的弹幕列表失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "获取指定时间范围内的弹幕列表失败");
        }
    }
    
    /**
     * 发送弹幕
     */
    @PostMapping("/danmaku")
    public CommonResponse<?> sendDanmaku(
            @RequestBody StudentCourseDanmaku danmaku) {
        log.info("发送弹幕 - 学生ID: {}, 课时ID: {}, 内容: {}, 时间点: {}", 
                danmaku.getStudentId(), danmaku.getLessonId(), danmaku.getContent(), danmaku.getTimePoint());
        
        try {
            // 检查课时是否存在
            Lesson lesson = lessonService.getById(danmaku.getLessonId());
            if (lesson == null) {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课时不存在");
            }
            
            // 发送弹幕
            boolean result = videoService.sendDanmaku(danmaku);
            
            if (result) {
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "发送成功", null);
            } else {
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "发送失败");
            }
        } catch (Exception e) {
            log.error("发送弹幕失败", e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "发送弹幕失败");
        }
    }
}